<template>
  <div class="file-detail">
    <Header />
    
    <main class="main-content">
      <div class="container">
        <div class="breadcrumb">
          <router-link to="/transfer">文件速递</router-link>
          <span class="separator">/</span>
          <span class="current">文件详情</span>
        </div>
        
        <div v-if="loading" class="loading-container">
          <div class="loading"></div>
          <p>加载中...</p>
        </div>
        
        <div v-else-if="fileInfo" class="detail-card">
          <div class="detail-header">
            <div class="file-icon-large">{{ getFileIcon(fileInfo.extension) }}</div>
            <h1 class="file-name">{{ fileInfo.oriName }}</h1>
            <div class="file-code">
              <span class="code-label">文件码：</span>
              <span class="code-value">{{ fileCode }}</span>
            </div>
          </div>
          
          <div class="detail-body">
            <div class="info-grid">
              <div class="info-item">
                <label>文件ID：</label>
                <span>{{ fileInfo.id }}</span>
              </div>
              
              <div class="info-item">
                <label>文件类型：</label>
                <span>{{ fileInfo.extension || '-' }}</span>
              </div>
              
              <div class="info-item">
                <label>文件大小：</label>
                <span>{{ formatFileSize(fileInfo.fileSize) }}</span>
              </div>
              
              <div class="info-item">
                <label>存储类型：</label>
                <span v-if="fileInfo.type === 0" class="badge badge-warning">按次数限制</span>
                <span v-else-if="fileInfo.type === 1" class="badge badge-info">按时间限制</span>
              </div>
              
              <div class="info-item">
                <label>上传时间：</label>
                <span>{{ formatDateTime(fileInfo.uploadTime) }}</span>
              </div>
              
              <div v-if="fileInfo.type === 0" class="info-item">
                <label>下载限制：</label>
                <span class="highlight-text">
                  {{ fileInfo.currentCount }} / {{ fileInfo.maxCount }} 次
                  <span v-if="fileInfo.currentCount >= fileInfo.maxCount" class="expired-tag">已用尽</span>
                </span>
              </div>
              
              <div v-if="fileInfo.type === 1" class="info-item">
                <label>过期时间：</label>
                <span class="highlight-text">{{ formatDateTime(fileInfo.expireTime) }}</span>
              </div>
            </div>
            
            <div v-if="fileInfo.type === 0 && fileInfo.currentCount >= fileInfo.maxCount" class="warning-notice">
              <div class="notice-icon">⚠️</div>
              <div class="notice-content">
                此文件下载次数已用尽，无法继续下载
              </div>
            </div>
          </div>
          
          <div class="detail-footer">
            <button 
              class="btn btn-primary btn-large" 
              @click="download"
              :disabled="downloading || isExpired"
            >
              <span v-if="downloading">⏳ 下载中...</span>
              <span v-else-if="isExpired">❌ 无法下载</span>
              <span v-else>⬇️ 下载文件</span>
            </button>
            
            <button class="btn" @click="goBack">
              返回
            </button>
          </div>
        </div>
        
        <div v-else class="error-state">
          <div class="error-icon">❌</div>
          <p>文件不存在或已过期</p>
          <button class="btn btn-primary" @click="goBack">
            返回
          </button>
        </div>
      </div>
    </main>
    
    <Footer />
    <Message ref="message" />
  </div>
</template>

<script>
import Header from '@/components/Header.vue'
import Footer from '@/components/Footer.vue'
import Message from '@/components/Message.vue'
import { getFileByCode, downloadFile } from '@/api/file'
import { formatFileSize, getFileIcon, formatDateTime } from '@/utils/format'

export default {
  name: 'FileTransferDetail',
  components: {
    Header,
    Footer,
    Message
  },
  data() {
    return {
      fileInfo: null,
      fileCode: '',
      loading: false,
      downloading: false
    }
  },
  computed: {
    isExpired() {
      if (!this.fileInfo) return true
      
      // 检查是否下载次数已用尽
      if (this.fileInfo.type === 0) {
        return this.fileInfo.currentCount >= this.fileInfo.maxCount
      }
      
      // 检查是否过期（虽然后端会检查，前端也可以做提示）
      if (this.fileInfo.type === 1 && this.fileInfo.expireTime) {
        const expireTime = new Date(this.fileInfo.expireTime).getTime()
        return Date.now() > expireTime
      }
      
      return false
    }
  },
  mounted() {
    // 从路由参数中获取文件信息
    this.fileCode = this.$route.query.code || ''
    
    // 如果路由参数中有文件信息，直接使用
    if (this.$route.params.fileInfo) {
      this.fileInfo = this.$route.params.fileInfo
    } else if (this.fileCode) {
      // 否则通过文件码重新查询
      this.loadFileInfo()
    }
  },
  methods: {
    formatFileSize,
    getFileIcon,
    formatDateTime,
    
    async loadFileInfo() {
      this.loading = true
      
      try {
        const response = await getFileByCode(this.fileCode)
        if (response.data.code === '0') {
          this.fileInfo = response.data.data
        } else {
          this.$refs.message.show({
            type: 'error',
            message: response.data.msg || '加载文件详情失败'
          })
        }
      } catch (error) {
        this.$refs.message.show({
          type: 'error',
          message: '加载文件详情失败：' + error.message
        })
      } finally {
        this.loading = false
      }
    },
    
    async download() {
      if (this.downloading || this.isExpired) return
      
      this.downloading = true
      
      try {
        const response = await downloadFile(this.fileInfo.id)
        
        // 创建下载链接
        const url = window.URL.createObjectURL(new Blob([response.data]))
        const link = document.createElement('a')
        link.href = url
        link.setAttribute('download', this.fileInfo.oriName)
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(url)
        
        this.$refs.message.show({
          type: 'success',
          message: '文件下载成功'
        })
        
        // 下载后重新加载文件信息（更新下载次数）
        if (this.fileInfo.type === 0) {
          setTimeout(() => {
            this.loadFileInfo()
          }, 1000)
        }
      } catch (error) {
        this.$refs.message.show({
          type: 'error',
          message: '文件下载失败：' + error.message
        })
      } finally {
        this.downloading = false
      }
    },
    
    goBack() {
      this.$router.push('/transfer')
    }
  }
}
</script>

<style scoped>
.file-detail {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.main-content {
  flex: 1;
  padding: 40px 0 80px;
}

.breadcrumb {
  margin-bottom: 24px;
  color: var(--text-secondary);
  font-size: 14px;
}

.breadcrumb a {
  color: var(--text-link);
}

.breadcrumb .separator {
  margin: 0 8px;
}

.breadcrumb .current {
  color: var(--text-primary);
}

.loading-container {
  text-align: center;
  padding: 100px 20px;
}

.loading-container p {
  margin-top: 16px;
  color: var(--text-secondary);
}

.detail-card {
  background-color: var(--bg-secondary);
  border: 1px solid var(--border-color);
  border-radius: 8px;
  overflow: hidden;
}

.detail-header {
  text-align: center;
  padding: 48px 32px;
  background: linear-gradient(135deg, rgba(210, 153, 34, 0.1) 0%, rgba(88, 166, 255, 0.1) 100%);
  border-bottom: 1px solid var(--border-color);
}

.file-icon-large {
  font-size: 96px;
  margin-bottom: 16px;
}

.file-name {
  font-size: 28px;
  font-weight: 600;
  word-break: break-word;
  margin-bottom: 16px;
}

.file-code {
  display: inline-block;
  padding: 8px 16px;
  background-color: var(--bg-tertiary);
  border: 1px solid var(--border-color);
  border-radius: 6px;
  font-family: monospace;
  font-size: 14px;
}

.code-label {
  color: var(--text-secondary);
  margin-right: 8px;
}

.code-value {
  color: var(--text-link);
  font-weight: 600;
  letter-spacing: 1px;
}

.detail-body {
  padding: 32px;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 24px;
  margin-bottom: 24px;
}

.info-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.info-item label {
  font-size: 14px;
  color: var(--text-secondary);
  font-weight: 500;
}

.info-item span {
  font-size: 16px;
  color: var(--text-primary);
}

.highlight-text {
  font-weight: 600;
  color: var(--primary-color);
}

.expired-tag {
  display: inline-block;
  margin-left: 8px;
  padding: 2px 8px;
  background-color: rgba(218, 54, 51, 0.2);
  color: var(--danger-color);
  border-radius: 4px;
  font-size: 12px;
}

.badge {
  display: inline-block;
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 14px;
  font-weight: 500;
  width: fit-content;
}

.badge-warning {
  background-color: rgba(210, 153, 34, 0.2);
  color: var(--warning-color);
}

.badge-info {
  background-color: rgba(88, 166, 255, 0.2);
  color: var(--text-link);
}

.warning-notice {
  display: flex;
  gap: 16px;
  padding: 20px;
  background-color: rgba(210, 153, 34, 0.1);
  border: 1px solid var(--warning-color);
  border-left: 4px solid var(--warning-color);
  border-radius: 8px;
}

.notice-icon {
  font-size: 24px;
  flex-shrink: 0;
}

.notice-content {
  color: var(--text-primary);
  line-height: 1.6;
}

.detail-footer {
  padding: 24px 32px;
  border-top: 1px solid var(--border-color);
  display: flex;
  gap: 16px;
  justify-content: center;
}

.btn-large {
  padding: 12px 32px;
  font-size: 16px;
}

.error-state {
  text-align: center;
  padding: 100px 20px;
}

.error-icon {
  font-size: 64px;
  margin-bottom: 16px;
}

.error-state p {
  color: var(--text-secondary);
  margin-bottom: 24px;
  font-size: 18px;
}

@media (max-width: 768px) {
  .info-grid {
    grid-template-columns: 1fr;
  }
  
  .detail-footer {
    flex-direction: column;
  }
  
  .btn-large {
    width: 100%;
  }
}
</style>

